package org.mili.ticketeer.ui.ticket;

import org.mili.application.service.ServiceException;
import org.mili.application.service.ServiceFactory;
import org.mili.application.ui.SimpleTableModel;
import org.mili.ticketeer.dto.Ticket;
import org.mili.ticketeer.service.GroupService;
import org.mili.ticketeer.service.PriorityService;
import org.mili.ticketeer.service.StateService;
import org.mili.ticketeer.service.TicketService;

import java.util.List;

/**
 */
public class TicketTableModel extends SimpleTableModel<Ticket> {
    private TicketService ticketService = ServiceFactory.getService(TicketService.class);
    private GroupService groupService = ServiceFactory.getService(GroupService.class);
    private StateService stateService = ServiceFactory.getService(StateService.class);
    private PriorityService priorityService = ServiceFactory.getService(PriorityService.class);

    public TicketTableModel() {
        super(new String[]{"No.", "Group", "State", "Title", "Priority", "CreatedAt", "CompletedAt", "Comment"});
        update();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Ticket ticket = get(rowIndex);
        switch(columnIndex) {
            case 0:
                return rowIndex + 1;
            case 1:
                try {
                    return groupService.findById(ticket.getGroup()).getName();
                } catch (ServiceException e) {
                    return "ERROR";
                }
            case 2:
                try {
                    return stateService.findById(ticket.getState()).getTitle();
                } catch (ServiceException e) {
                    return "ERROR";
                }
            case 3:
                return ticket.getTitle();
            case 4:
                try {
                    return priorityService.findById(ticket.getPriority()).getName();
                } catch (ServiceException e) {
                    return "ERROR";
                }
            case 5:
                return ticket.getCreatedAt();
            case 6:
                return ticket.getCompletedAt();
            case 7:
                return ticket.getComment();
            default: throw new IllegalStateException("no column index for: " + columnIndex);
        }
    }

    @Override
    public List<Ticket> load() {
        try {
            return ticketService.getTickets();
        } catch (ServiceException e) {
            throw new IllegalStateException(e);
        }
    }

}
